﻿using System;
using System.IO;
using System.Net;
using System.Text;
using JetBrains.Annotations;
using SF.Code.Extension.HttpHelper;
using SF.Code.Extension.NetworkHelper;

namespace SG.Ling.AutoTranslator.App
{
    partial class Program
    {
        private SimpleHttpServer _httpServer;

        private void StartHttpServer()
        {
            _httpServer = new SimpleHttpServer(TranslatorForm.Icon,
                                               new EndpointReservation(IPAddress.Loopback,
                                                                       new Port(IpTransportProtocol.Tcp, 80), uriPart: "/translator/"));
            _httpServer.StartAsync(GetMainPage, GetExceptionPage);
        }

        [NotNull]
        private static string GetMainPage(SimpleHttpServer server)
        {
            var builder = new StringBuilder(5*1024);
            using (var writer = new StringWriter(builder))
            {
                writer.WriteLine(@"<!DOCTYPE html>
<html>
    <header>
        <link rel=""shortcut icon"" href=""favicon.ico"">
        <title>Translate.NET</title>
    <header>
    <body>
    </body>
</html>");
            }

            return builder.ToString();
        }

        private static string GetExceptionPage(SimpleHttpServer server, Exception exception)
        {
            var builder = new StringBuilder(5 * 1024);
            using (var writer = new StringWriter(builder))
            {
                writer.WriteLine("<!DOCTYPE html>");
                writer.WriteLine("<html><header><title>Translate.NET</title><header><body>");
                writer.WriteLine(exception.Message);
                writer.WriteLine("</body></html>");
            }

            return builder.ToString();    
        }
    }
}
